package org.msb.accentis.data.pojo;

import java.util.Date;

import javax.persistence.*;

@Entity
@NamedQueries({ @NamedQuery(name = "Individual.getAllIndividuals", query = "SELECT i FROM Individual i ORDER BY i.name"),
		@NamedQuery(name = "Individual.getIndividual", query = "SELECT i FROM Individual i WHERE i.id = :id"),
		@NamedQuery(name = "Individual.getFilteredIndividualList", query = "SELECT i FROM Individual i WHERE i <> :excludedIndividual"),
		@NamedQuery(name = "Individual.getTransactionDetailsWithIndividual", query = "SELECT td FROM TransactionDetail td WHERE td.individual = :individual") })
public class Individual extends NamedObject {

	@Embedded
	private SIN sin;

	@Temporal(TemporalType.DATE)
	private Date birthDate;

	@OneToOne(targetEntity = Individual.class, fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
	private Individual spouse;

	@OneToOne(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
	private Image picture;

	public Individual() {
	}

	public SIN getSIN() {
		return sin;
	}

	public void setSIN(SIN sin) {
		this.sin = sin;
	}

	public Date getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Date date) {
		birthDate = (null == date ? null : (Date) date.clone());
	}

	public Image getPicture() {
		return picture;
	}

	public void setPicture(Image value) {
		picture = value;
	}

	public Individual getSpouse() {
		return spouse;
	}

	public void setSpouse(Individual individual) {
		unlinkSpouse(this);
		unlinkSpouse(individual);
		linkSpouse(this, individual);
	}

	@PreRemove
	public void updateSpouse() {
		if (null != spouse) {
			spouse.spouse = null;
		}
	}

	private static void unlinkSpouse(Individual individual) {
		if (null != individual && null != individual.spouse) {
			individual.spouse.spouse = null;
			individual.spouse = null;
		}
	}

	private static void linkSpouse(Individual individual1, Individual individual2) {
		individual1.spouse = individual2;

		if (null != individual2)
			individual2.spouse = individual1;
	}
}
